package cc.aliza.lib.mongo.core.utils;

import cc.aliza.lib.mongo.core.annotations.Id;
import cc.aliza.lib.mongo.core.cache.FieldsCache;
import org.bson.types.ObjectId;

import java.lang.reflect.Field;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public class IdUtil {

    public static Object toDbId(Class<?> clazz, Object id) {
        if (id instanceof ObjectId) {
            return id;
        }

        String idStr = (String) id;

        if (StringUtil.isEmpty(idStr)) {
            return null;
        }

        Object result = null;
        Field idField = FieldsCache.getInstance().getIdField(clazz);
        Id idAnnotation = idField.getAnnotation(Id.class);
        switch (idAnnotation.type()) {
            case AUTO_GENERATE:
                result = new ObjectId(idStr);
                break;
            case AUTO_INCREASE:
                result = Long.parseLong(idStr);
                break;
            case USER_DEFINE:
                result = idStr;
                break;
        }
        return result;
    }
}
